import datetime as dt
from pymongo import MongoClient
from umongo import Document, fields, validate
from umongo.frameworks import PyMongoInstance

db = MongoClient().temp     # 选择Mongo中的test数据库
instance = PyMongoInstance(db)  # 创造test数据库实例（用umongo操作）

@instance.register
class User(Document):
    email = fields.EmailField(required=True)
    birthday = fields.DateTimeField(validate=validate.Range(min=dt.datetime(1900, 1, 1)))
    friends = fields.ListField(fields.ReferenceField("User"))

    class Meta:
        collection_name = "user"    # 数据库的表名为user

# Make sure that unique indexes are created
User.ensure_indexes()

goku = User(email='goku@sayen.com', birthday=dt.datetime(1984, 11, 20))
temp1 = goku.commit()
vegeta = User(email='vegeta@over9000.com', friends=[goku])
temp = vegeta.commit()

# print(vegeta.friends)
print(temp1.acknowledged)
print(temp.acknowledged)
# <object umongo.data_objects.List([<object umongo.dal.pymongo.PyMongoReference(document=User, pk=ObjectId('5717568613adf27be6363f78'))>])>

# vegeta.dump()
# {id': '570ddb311d41c89cabceeddc', 'email': 'vegeta@over9000.com', friends': ['570ddb2a1d41c89cabceeddb']}

# print(User.find_one({"email": 'goku@sayen.com'}))
# <object Document __main__.User({'id': ObjectId('570ddb2a1d41c89cabceeddb'), 'friends': <object umongo.data_objects.List([])>,
#                                 'email': 'goku@sayen.com', 'birthday': datetime.datetime(1984, 11, 20, 0, 0)})>